/**
 *  路由守卫
 */
import router from "./router";
import store from "./store";
import {
	Message
} from "element-ui";
import NProgress from "nprogress"; // 进度条
import "nprogress/nprogress.css"; // 进度条样式
import {
	getToken
} from "@/utils/auth"; // 从cookie获取token
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({
	showSpinner: false
}); // 进度条配置

const whiteList = ["/login"]; // 白名单路由

router.beforeEach(async (to, from, next) => {
	// 开始进度条
	NProgress.start();

	// 设置页面Title
	document.title = getPageTitle(to.meta.title);

	// 确认用户是否已登录
	const hasToken = getToken();
	if (hasToken) {
		if (to.path === "/login") {
			// 如果已登录，则重定向到主页
			next({
				path: "/"
			});
			NProgress.done();
		} else {

			if (store.getters.permission_isAddRoutes) {

				if (to.matched.length === 0) {
					next("/404");
				}
				next();
			} else {
				try {
					// 获取用户权限菜单
					const accessRoutes = await store.dispatch(
						"permission/generateRoutes"
					);
					router.addRoutes(accessRoutes);
					next({
						...to,
						replace: true
					});
				} catch (error) {
					// 删除Token，跳转到登录页
					await store.dispatch("user/resetToken");
					next({
						path: "/"
					});
					NProgress.done();
				}
			}
		}
	} else {
		/* 未登录 */
		if (whiteList.indexOf(to.path) !== -1) {
			// 在白名单中的页面直接进入
			next();
		} else {
			// 其他页面重定向到登录页
			next(`/login?redirect=${to.path}`);
			NProgress.done();
		}
	}
});

router.afterEach(() => {
	// 完成进度条
	NProgress.done();
});
